package com.spzx.order.receiver;

import com.rabbitmq.client.Channel;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.order.service.IOrderInfoService;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class OrderReceiver {

    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    //接收端：根据订单编号更新订单状态
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_PAYMENT_PAY, durable = "true"),
            value = @Queue(value = MqConst.QUEUE_PAYMENT_PAY, durable = "true"),
            key = MqConst.ROUTING_PAYMENT_PAY
    ))
    public void processPaySucess(String orderNo,Message message,Channel channel) {
        if(StringUtils.hasText(orderNo)) {
            //调用方法更新状态
            orderInfoService.updateOrderStatus(orderNo);
        }

        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    @SneakyThrows
    @RabbitListener(queues = MqConst.QUEUE_CANCEL_ORDER)
    public void processCloseOrder(String orderId, Message message, Channel channel) {

        //获取发送过来orderid，根据orderid取消订单
        if(orderId != null) {
            //加锁
            String key = "close:lock:"+orderId;
            String value = "close:value:"+orderId;

            Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(key, value, 10, TimeUnit.SECONDS);

            if(ifAbsent) { //true加锁成功，第一次消费
                try {
                    //调用service方法取消订单
                    orderInfoService.processCloseOrder(orderId);
                }catch (Exception e) {
                    redisTemplate.delete(key);
                }
            }
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }


}
